<template>
  <view class="u-page">
    <u--form ref="form" labelPosition="top" labelWidth="100%" :labelStyle="labelStyle" :model="form" :rules="rules">
      <u-form-item label="集资参与人身份证正面" prop="idCardPositiveUrl">
        <u-upload
          accept="image"
          :compressed="false"
          capture="camera"
          width="360"
          height="240"
          name="idCardPositiveUrl"
          maxCount="1"
          :fileList="idCardPositiveUrl"
          @beforeRead="loading()"
          @afterRead="uploadFile($event, atterUploadCardPositive)"
          @delete="deleteFile($event, atterDeleteFile)"
        >
          <image src="../../static/card-positive.png" mode="widthFix" class="card-img"></image>
        </u-upload>
      </u-form-item>
      <u-form-item label="集资参与人身份证反面" prop="idCardBackUrl">
        <u-upload
          accept="image"
          capture="camera"
          width="360"
          height="240"
          name="idCardBackUrl"
          maxCount="1"
          :fileList="idCardBackUrl"
          @afterRead="uploadFile($event, atterUploadCardBack)"
          @delete="deleteFile($event, atterDeleteFile)"
        >
          <image src="../../static/card-back.png" mode="widthFix" class="card-img"></image>
        </u-upload>
      </u-form-item>
      <u-form-item label="集资参与人证件号" prop="idCardNo">
        <u--input v-model="form.idCardNo" required placeholder="请输入集资人证件号" disabled></u--input>
      </u-form-item>
	  <u-form-item label="证件有效期" prop="losedDate">
	    <u--input v-model="form.losedDate" disabled></u--input>
	  </u-form-item>
      <u-form-item label="办理人" prop="oneself">
        <u-radio-group v-model="form.oneself" placement="row" @change="transactorChange">
          <u-radio
            size="40"
            labelSize="40"
            :customStyle="{ marginBottom: '8px' }"
            v-for="(item, index) in oneselflist"
            :key="index"
            :label="item.label"
            :name="item.name"
          ></u-radio>
        </u-radio-group>
      </u-form-item>
      <u-form-item class="mt-2">
        <u-row class="w-100" justify="center">
          <u-col span="6" justify="center">
            <u-button type="primary" shape="circle" @click="confirm"><view>下一步</view></u-button>
          </u-col>
        </u-row>
      </u-form-item>
    </u--form>
    <u-row class="mt-4">
      <u-col span="12"><uni-steps :options="stepList" :active="currentStepIndex"></uni-steps></u-col>
    </u-row>
  </view>
</template>

<script>
import { checkIdNumber } from '@/util/validate.js';
import { baseFont, mcStepKey } from '@/common/config.js';
import { getAccessToken, idCardOCR, idCardOCRBack } from '@/common/baiduApi.js';
import { pathToBase64 } from 'image-tools';
import { checkSave } from '@/common/api/mcRegister.js';
import { uploadImage } from '@/common/api/common.js';

export default {
  data() {
    return {
      preStep: mcStepKey.step1,
      currentStep: mcStepKey.step1,
      nextStep: mcStepKey.step2,
      currentStepIndex: 0,
      labelStyle: { fontSize: baseFont + 'upx', marginBottom: '10upx' },
      form: {
        idCardPositiveUrl: '',
        idCardFaceUrl: '',
        idCardFaceBase64: '',
        idCardBackUrl: '',
        idCardNo: '',
        oneself: true,
        actualInvestmentAmount: null,
        actualAmountOfPrincipalAndInterestReturned: null,
        actualLossAmount: null,
        actualAmountOfLossToBeReturned: null,
        idCardBase64: '',
        copyIdCardNo: '',
		losedDate: ''
      },
      rules: {
        idCardPositiveUrl: {
          type: 'string',
          required: true,
          message: '请上传集资参与人身份证正面',
          trigger: ['blur'],
        },
        idCardBackUrl: {
          type: 'string',
          required: true,
          message: '请上传集资参与人身份证反面',
          trigger: ['blur'],
        },
        idCardNo: [
          {
            type: 'string',
            required: true,
            message: '请填写集资参与人证件号',
            trigger: ['blur', 'change'],
          },
          { validator: checkIdNumber, trigger: ['blur', 'change'] },
        ],
      },
      idCardPositiveUrl: [],
      idCardBackUrl: [],
      oneselflist: [{ name: true, label: '集资参与人' }],
      noticeShow: false,
      // 等待时间
      timeHaveToStay: 10,
      noticeBtn: true,
    };
  },
  onLoad(options) {
    this.checkMcPage(options);
    this.imageBackShow(['idCardPositiveUrl', 'idCardBackUrl']);
    if (this.oneself) {
      this.nextStep = mcStepKey.step2;
    } else {
      this.nextStep = mcStepKey.step1_5;
    }
    this.noticeShow = true;
    this.stayTimerF();
  },
  beforeDestroy() {
    this.clearTimer();
  },
  methods: {
    clearTimer() {
      this.stayTimer && clearTimeout(this.stayTimer);

      this.stayTimer = null;
    },
    stayTimerF() {
      this.stayTimer = setTimeout(() => {
        if (--this.timeHaveToStay === 0) {
          this.noticeBtn = false;
          return;
        }
        this.stayTimerF();
      }, 1000);
    },
    loading() {
      uni.showLoading({
        title: '请稍后...',
      });
    },
    // 上传身份证正面
    async atterUploadCardPositive(fileList) {
      this.form.idCardPositiveUrl = fileList[0].url;
      this.$refs.form.validateField('idCardPositiveUrl');
      const imageBase64 = await pathToBase64(fileList[0].thumb);
      const accessToken = await getAccessToken();
      const { data } = await idCardOCR(imageBase64, accessToken);

      if (data.idcard_number_type == -1) {
        this.form.idCardFaceBase64 = '';
		this.form.idCardPositiveUrl = [];
		this.idCardPositiveUrl = [];
		uni.$u.toast('请上传本人清晰的身份证！');
		uni.hideLoading();
        return;
      }
      const idCard = data.words_result['公民身份号码'].words;
      if (!idCard || idCard !== this.form.idCardNo) {
        this.form.idCardPositiveUrl = [];
        this.idCardPositiveUrl = [];
        uni.$u.toast('请上传本人清晰的身份证！');
        uni.hideLoading();
        return;
      }
      this.form.copyIdCardNo = idCard;
      // 识别出证件保存
      this.form.idCardNo = idCard;
      this.$refs.form.validateField('idCardNo');
      // 识别图片保存
      const photo = data.photo;
      const { fileName } = await uploadImage(photo);
      this.form.idCardFaceBase64 = photo;
      this.form.idCardFaceUrl = fileName;
      uni.hideLoading();
    },
    // 删除身份证正面
    atterDeleteCardPositive(fileList) {
      this.form.idCardPositiveUrl = '';
      this.$refs.form.validateField('idCardPositiveUrl');
    },
    // 上传身份证反面
    async atterUploadCardBack(fileList) {
      this.form.idCardBackUrl = fileList[0].url;
      this.$refs.form.validateField('idCardBackUrl');
	  
	  const imageBase64 = await pathToBase64(fileList[0].thumb);
	  const accessToken = await getAccessToken();
	  const { data } = await idCardOCRBack(imageBase64, accessToken);
	  
	  const ld = data.words_result['失效日期'];
	  if (!ld) {
		  uni.$u.toast('请上传身份证证件照国徽面！');
		  this.form.idCardBackUrl = '';
		  return;
	  }
	  const qf = data.words_result['签发日期'];
	  const loseDate = ld.words;
	  const qfDate = qf.words;
	  if (loseDate) {
		  let start = qfDate.substring(0,4) + '.' + qfDate.substring(4, 6) + '.' + qfDate.substring(6, 8) ;
		  let end = loseDate.substring(0,4) + '.' + loseDate.substring(4, 6) + '.' + loseDate.substring(6, 8) ;
		  this.form.losedDate = start + ' 至 ' + end;
	    let newDate = new Date();
		let year = newDate.getFullYear();
		let month = newDate.getMonth().toString().padStart(2,0);
		let day = newDate.getDay().toString().padStart(2,0);
		let dt = year +  month  + day;
		if (parseInt(loseDate) <= parseInt(dt)) {
			this.form.idCardBackUrl = '';
			uni.$u.toast('您的证件已过期！');
			uni.hideLoading();
			return;
		}
	  }
	  uni.hideLoading();
    },
    // 删除身份证反面
    atterDeleteCardBack(fileList) {
      this.form.idCardBackUrl = '';
      this.$refs.form.validateField('idCardBackUrl');
    },
    // 下一步
    confirm() {
      let that = this;
      that.$refs.form.validate().then(res => {
        this.toNextMcPage(this.idCard);
      });
    },
    // 切换办理人
    transactorChange(value) {
      this.oneself = value;
      if (this.oneself) {
        this.nextStep = mcStepKey.step2;
		
		this.rules.idCardPositiveUrl.required = true;
		this.rules.idCardBackUrl.required = true;
      } else {
        this.nextStep = mcStepKey.step1_5;
		
		this.rules.idCardPositiveUrl.required = false;
		this.rules.idCardBackUrl.required = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.active-color {
  color: $u-primary;
}
</style>
